import cv2
import numpy as np

cur_shape = 0
start_pos = (0, 0)


def mouse_callback(event, x, y, flags, user_data):
    # print(event, x, y, flags, user_data)
    global cur_shape, start_pos
    if event & cv2.EVENT_LBUTTONDOWN == cv2.EVENT_LBUTTONDOWN:

        start_pos = (x, y)
    elif event & cv2.EVENT_LBUTTONUP == cv2.EVENT_LBUTTONUP:
        if cur_shape == 0:
            cv2.line(img, start_pos, (x, y), (0, 0, 255))
        elif cur_shape == 1:
            cv2.rectangle(img, start_pos, (x, y), (0, 0, 255))
        elif cur_shape == 2:
            a = (x - start_pos[0])
            b = (y - start_pos[1])
            r = int((a ** 2 + b ** 2) ** 0.5)
            cv2.circle(img, start_pos, r, (0, 0, 255))
        else:
            print("error: no shape")
    elif flags == 1:
        # print("EVENT_MOUSEMOVE")
        if cur_shape == 0:
            img[:] = 0
            cv2.line(img, start_pos, (x, y), (0, 0, 255))
        elif cur_shape == 1:
            maxY = max(start_pos[1], y)
            minY = min(start_pos[1], y)
            maxX = max(start_pos[0], x)
            minX = min(start_pos[0], x)
            img[minY:maxY, minX: maxX] = 0
            cv2.rectangle(img, start_pos, (x, y), (0, 0, 255))
        elif cur_shape == 2:
            img[:] = 0
            a = (x - start_pos[0])
            b = (y - start_pos[1])
            r = int((a ** 2 + b ** 2) ** 0.5)
            cv2.circle(img, start_pos, r, (0, 0, 255))
        else:
            print("error: no shape")


img = np.zeros((480, 640, 3), np.uint8)
cv2.namedWindow('all', cv2.WINDOW_NORMAL)
cv2.resizeWindow('all', 480, 640)
cv2.setMouseCallback('all', mouse_callback, "123")

while True:
    cv2.imshow('all', img)
    key = cv2.waitKey(10)
    if key & 0xFF == ord('q'):
        break
    elif key & 0xFF == ord('l'):
        cur_shape = 0
    elif key & 0xFF == ord('r'):
        cur_shape = 1
    elif key & 0xFF == ord('c'):
        cur_shape = 2

cv2.destroyAllWindows()
